--bridge.lua
function log(str)
	freeswitch.consoleLog("INFO",str.."\n")
end
local api = freeswitch.API()
local channelUuid = argv[1]
local memberUuid = argv[2]
local dest = argv[3]
local leg_timeout = api:executeString("uuid_getvar "..channelUuid .. " no_answer_timeout")
local callerIdNumber = api:executeString("uuid_getvar "..channelUuid .. " call_in_destination_number")
if callerIdNumber ~= nil then
	log("uuid_getvar call_in_destination_number : " ..callerIdNumber)
else
	log("call_in_destination_number null")
	return;
end

api:executeString("uuid_setvar "..channelUuid .. " opbx_queue_member "..dest )
api:executeString("uuid_setvar "..channelUuid .. " station " .. dest)
api:executeString("uuid_setvar "..channelUuid .. " bridged_member_uuid "..memberUuid)

local params = "opbx_originator="..channelUuid..",origination_uuid="..memberUuid..",opbx_queue_member="..dest..",station="..dest..",origination_caller_id_number="..callerIdNumber..",origination_caller_id_name="..callerIdNumber
if leg_timeout ~= nil and leg_timeout ~= "" then
	params = params .. ",originate_timeout="..leg_timeout..",ignore_early_media=true"
end

local bleg = freeswitch.Session("{"..params.."}user/"..dest)
if bleg:ready() then
	bleg:setAutoHangup(false)
	bleg:waitForAnswer()
	while bleg:ready() do
		if bleg:answered() then
			log("bridge !member->channel:".. memberUuid .. " -> "..channelUuid)
			api:executeString("uuid_bridge ".. channelUuid .. " " .. memberUuid)
			break
		else
			freeswitch.msleep(200)
		end
	end
else
	log("originate " ..memberUuid.." failed!")
end

